import axios from 'axios';
import { reactive } from "vue";

import { ElMessage } from 'element-plus'


// /ltapi   http://47.99.66.117:5501
const instance = axios.create({
    baseURL: 'http://47.99.66.117:5501', // 设置请求的基础URL
    timeout: 5000, // 设置请求超时时间
});

// 添加响应拦截器
instance.interceptors.response.use(
    (response: any) => {
        let resdata: any
        
        if (response.data[0] && response.data[0].productAssetList !== null) {
            let resdata2: any[] = [];
            for (let item of response.data) {
                let items = item
                items.productAssetList = JSON.parse(item.productAssetList)
                items.productAssets = JSON.parse(item.productAssets)
                // if (item.series.length > 5) {
                //   items.series =  JSON.parse(item.series)
                // }

                resdata2.push(items)
            }

            resdata = resdata2
        } else if (response.data.page) {
            let resdata2: any[] = [];
            for (let item of response.data.data) {
                let items = item
                items.productAssetList = JSON.parse(item.productAssetList)
                items.productAssets = JSON.parse(item.productAssets)
                // if (item.series.length > 5) {
                //   items.series =  JSON.parse(item.series)
                // }

                resdata2.push(items)
            }

            resdata = {
                data: resdata2,
                pageCount: response.data.pageCount,
                limit: response.data.limit,
                page: response.data.page
            }
        } else {
            resdata = response.data
        }
        if (resdata.code !== 200) {
            ElMessage.error('请求失败')
        }
        return resdata;
    },
    (error: any) => {
        // 对响应错误进行处理
        if (error.message.indexOf('timeout') != -1) {
			ElMessage.error('网络超时');
		} else if (error.message == 'Network Error') {
			ElMessage.error('网络连接错误');
		} else {
			ElMessage.error('接口路径找不到');
		}
        return Promise.reject(error);
    }
);

// 添加响应拦截器
instance.interceptors.request.use((config) => {
    const token = localStorage.getItem('token'); // 从localStorage中获取token，您可以根据实际情况进行修改
    if (token) {
        config.headers.authorization = localStorage.getItem('token'); // 在请求头部中添加token
    }

    return config;
});

export default instance;